$(function(){
    var dsgId = [],contentBool = false,imageUrlBool = false,
    content=[],imageUrl=[],designerList=[];
    var code = $.getUrlParam('code');
    goBackFn();
    getData(code);
    choosePic();
    chooseFn();
    submitDataFn();

    // FUN  
    function goBackFn(){
        $('.goBack').click(function(){
            go(localStorage.getItem("_url"))
        })
    }

    function getData(code){
        post({
            url:'/customizeOrder/designerList',
            data:{code:code},
            success:function(data){
                dealWithDataA(data);
                dealWithDataB(data);
                dealWithPic(data);
                for(let i=0;i<data.length;i++){
                    dsgId.push(data[i]['id']);
                }
            }
        });
        post({
            url:'/customizeOrder/findMember',
            success:function(data){
                console.log(data)
                $('.contextName').val(data.contact);
                $('.contextPhone').val(data.contactTel);
            }
        })
    };


    function dealWithDataA(data){
        for(let i = 0; i<data.length; i++){
            $('.secContext').append(
                `
                <aside name="${data[i]['id']}" class="aside_${data[i]['id']} tab">
                    <div class="secContext_header"></div>
                </aside>
                `
            );
            $('.secChoose').append(
                `
                <div name="${data[i]['id']}" class="choose_${data[i]['id']}">${data[i]['name']}</div>
                `
            );
        }
    };

    function dealWithDataB(data){
        for(let i = 0; i<data.length; i++){
            let status = data[i]['designContent']['name'];
            switch (status) {
                case 'PICTURE':
                    $('.aside_'+data[i]['id']).append(
                        `
                        <div class="asideSwitch aside_pic_${data[i]['id']} tab">
                            <img class="aside_picAction aside_picAction_${data[i]['id']}" src="./img/kongImg.png" alt="">
                            <div class="asidePicGroup">
                                <input name="${data[i]['id']}" class="upPic upPic_${data[i]['id']}" type="file"/>
                                <img class="aside_picData aside_picData_${data[i]['id']}" src="./img/shangchaun.png" alt="">
                                <img  src="./img/moban.png" alt="">
                            </div>
                        </div>
                        `
                    );
                    $('.aside_'+data[i]['id']+'>.secContext_header').append(
                        `
                        <span name="addPic_${data[i]['id']}" class="addPic_${data[i]['id']}"><i>添加图片</i></span>
                        `
                    )
                    break;
                case 'PICANDCHAR':
                    $('.aside_'+data[i]['id']).append(
                        `
                        <textarea class="asideSwitch aside_text_${data[i]['id']} tab"></textarea>
                        <div class="asideSwitch aside_pic_${data[i]['id']} tab">
                            <img class="aside_picAction aside_picAction_${data[i]['id']}" src="./img/kongImg.png" alt="">
                            <div class="asidePicGroup">
                                <input name="${data[i]['id']}" class="upPic upPic_${data[i]['id']}" type="file"/>
                                <img class="aside_picData aside_picData_${data[i]['id']} upPicData_${data[i]['id']}" src="./img/shangchaun.png" alt="">
                                <img  src="./img/moban.png" alt="">
                            </div>
                        </div>
                        `
                    );
                    $('.aside_'+data[i]['id']+'>.secContext_header').append(
                        `
                        <span name="addText_${data[i]['id']}" class="addText_${data[i]['id']}"><i>添加文字</i></span>
                        <span name="addPic_${data[i]['id']}" class="addPic_${data[i]['id']}"><i>添加图片</i></span>
                        `
                    )
                    break;
                case 'CHARACTER':
                    $('.aside_'+data[i]['id']).append(
                        `
                        <textarea class="asideSwitch aside_text_${data[i]['id']}"></textarea>
                        `
                    );
                    $('.aside_'+data[i]['id']+'>.secContext_header').append(
                        `
                        <span name="addText_${data[i]['id']}" class="addText_${data[i]['id']}"><i>添加文字</i></span>
                        `
                    )
                    break;
            
                default:
                    break;
            }
        }
    }

    //照片上传函数
    function uploadPic(dom, url, target) {
        var fd = new FormData();
        fd.append("file", $(dom).get(0).files[0]);
        var size = $(dom)[0].files[0].size;
        var type = $(dom)[0].files[0].type;
        if(size<=6*1024*1024){
            if(type == 'image/jpeg' || type == 'image/png'){
                $.ajax({
                    url: SERVER_CONTEXT_PATH + url,
                    type: 'POST',
                    data: fd,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log(data)
                        $(target).attr("src", SERVER_CONTEXT_PATH + "/load/picture/" + data);
                        // post({
                        //     url: '/member/uploadAvatar',
                        //     data:{imageCode:data},
                        //     success: function (data) {
                        //         console.log(data)
                        //     }
                        // })
                    },
                    error:function(msg){
                        messageAlert(msg);
                    }
                });
            }else{
                messageAlert('请上传jpg/png格式的照片!');
            }
        }else{
            messageAlert('上传照片不能大于6M!');
        }
    }

    function dealWithPic(data){
            for(let i=0;i<data.length;i++){
                console.log(data);
                console.log(data[i]["pictureList"]);
                if(!data[i]["pictureList"]){
                    
                }else{
                    for(let j=0; j<data[i]["pictureList"].length; j++){
                        $('.aside_pic_'+data[i]['id']+'>.asidePicGroup').append(
                            `
                            <img name="aside_picData_${data[i]['id']}" class="aside_picData aside_picData_${data[i]['id']}" src="${SERVER_CONTEXT_PATH}/load/picture/${data[i]["pictureList"][j]}" alt="">
                            `
                        )
                    }
                }
                
            }
        $('.secContext').delegate('.upPic','change',function(){
            console.log($(this).attr('name'))
            let num = $(this).attr('name');
            uploadPic($(this), '/upload/picture', '.aside_picAction_'+num)
        })
    }

    function choosePic(){
        $('.secContext').delegate('.aside_picData','click',function(){
            let PicNum = $(this).attr('name').split('_')[2];
            let PicSrc = $(this).attr('src');
            $('.aside_picData_'+PicNum).removeClass('redBorder');
            $(this).addClass('redBorder')
            $('.aside_picAction_'+PicNum).attr('src',PicSrc);
        })
    }

    function submitDataFn(){
        $('.submitBtn').click(function(){
            for(let i=0; i<dsgId.length; i++){
                if($('.aside_text_'+dsgId[i]).val()){
                    content.push($('.aside_text_'+dsgId[i]).val());
                }else{
                    content.push('');
                }
                if($('.aside_picAction_'+dsgId[i]).attr('src')=='./img/kongImg.png'){
                    imageUrl.push('');
                }else if($('.aside_picAction_'+dsgId[i]).attr('src')){
                    imageUrl.push($('.aside_picAction_'+dsgId[i]).attr('src').split('load/picture/')[1]);
                }else{
                    imageUrl.push('');
                }
            };
            for(let i=0; i<dsgId.length; i++){
                designerList.push({
                    'dsgId':dsgId[i],
                    'content':content[i],
                    'imageUrl':imageUrl[i]
                })
            }
            for(let i=0;i<content.length;i++){
                if(content[i]){
                    contentBool=true;
                }
            }
            for(let i=0;i<imageUrl.length;i++){
                if(imageUrl[i]){
                    imageUrlBool=true;
                }
            }
            if((imageUrlBool||contentBool)&&$('.contextName').val()&&$('.contextPhone').val()){
                submitFn();
            }else{
                alert('请将信息填写完整。');
            }
        })
    }

    function submitFn(){
        console.log(designerList)
        var data = {
            designerList:designerList,
            code:code,
            contact:$('.contextName').val(),
            contactTel:$('.contextPhone').val()
        }
        post({
            url:'/customizeOrder/saveOrderTemporary',
            data:data,
            success:function(data){
                setCookie("confirmCustomCode",code);
                go('/mobileorder/confirmCustom.html');
            }
        })
    }

    function chooseFn(){      //选择器
        $('.secChoose').delegate('div','click',function(){
            var chooseNum = $(this).attr('name');
            $(".secContext>.aside_1>img,.secContext>img").addClass("tab");
            $(this).addClass('asideAction').siblings().removeClass('asideAction');
            $('aside').addClass('tab');
            $('.aside_'+chooseNum).removeClass('tab');
            $('.asideSwitch').addClass('tab');
            $('.aside_text_'+chooseNum).removeClass('tab');
            $('.addText_'+chooseNum).addClass('asideAction_');
            $('.addPic_'+chooseNum).removeClass('asideAction_');
        });
        $('.secContext').delegate('span','click',function(){
            var chooseNum = $(this).attr('name').split('_')[1];
            var chooseName = $(this).attr('class').split('_')[0];
            $(".secContext>.aside_1>img").addClass("tab");
            switch (chooseName) {
                case 'addText':
                    $('.asideSwitch').addClass('tab');
                    $('.aside_text_'+chooseNum).removeClass('tab');
                    break;
                case 'addPic':
                    $('.asideSwitch').addClass('tab');
                    $('.aside_pic_'+chooseNum).removeClass('tab');
                    break;
                default:
                    break;
            }
            $(this).addClass('asideAction_').siblings().removeClass('asideAction_');
        });
        $('.contextPhone').blur(function(){
            var ExgStr = /^1[34578]\d{9}$/;
            if(!ExgStr.test($('.contextPhone').val())){
                $('.contextPhone').val('');
            }
        });
    };
})